from django.db import models
from django.core.exceptions import ObjectDoesNotExist

class MailDomain(models.Model):
	id = models.AutoField('ID', primary_key=True, db_column="pkid")
	domain = models.CharField(maxlength=120)
	transport = models.CharField(maxlength=120, default="virtual:", editable=False)
	enabled = models.BooleanField(default=True, editable=False)
	
	class Meta:
		db_table = "domains"
		verbose_name="Mail Domain"
		verbose_name_plural="Mail Domains"
	
	def __str__(self):
		return self.domain
	
	def save(self):
		if not self.id:
			self.enabled = True
			self.transport = "virtual:"
		super(MailDomain, self).save()
	
	class Admin:
		pass

class MailAlias(models.Model):
	id = models.AutoField('ID', primary_key=True, db_column="pkid")
	address = models.CharField(maxlength=120, unique=True, db_column="mail")
	forwards_to = models.CharField(maxlength=120, db_column="destination")
	enabled = models.BooleanField(default=True, editable=False)
	
	class Meta:
		db_table = "aliases"
		verbose_name_plural="Mail Aliases"
		verbose_name="Mail Alias"
	
	def __str__(self):
		if self.address == self.forwards_to:
			return self.address
		else:
			return self.address + "=>" + self.forwards_to
	
	class Admin:
		pass

class MailUser(models.Model):
	address= models.CharField(maxlength=128, primary_key=True, unique=True, db_column="id")
	name = models.CharField(maxlength=128)
	maildir = models.CharField(maxlength=255)
	password = models.CharField(maxlength=128, db_column="clear")
	uid = models.IntegerField(default=5000, editable=False)
	gid = models.IntegerField(default=5000, editable=False)
	home = models.CharField(maxlength=255, default="/var/spool/mail/virtual", editable=False)
	enabled = models.BooleanField(default=True, editable=False)
	change_password = models.BooleanField(default=True, editable=False)
	crypt = models.CharField(maxlength=128, default='', editable=False)
	quota = models.CharField(maxlength=255, default='', editable=False)
	procmailrc = models.CharField(maxlength=128, default='', editable=False)
	spamassassinrc = models.CharField(maxlength=128, default='', editable=False)
	
	class Meta:
		db_table = "users"
		verbose_name="Mail Account"
		verbose_name_plural="Mail Accounts"
	
	def __str__(self):
		return self.address
	
	def save(self):
		try:
			a = MailAlias.objects.get(address=self.address)
		except ObjectDoesNotExist:
			a = MailAlias(address=self.address, forwards_to=self.address, enabled=True)
			a.save()
		super(MailUser, self).save()
	
	def delete(self):
		a = MailAlias.objects.get(address=self.address)
		a.delete()
		super(MailUser, self).delete()
	
	class Admin:
		pass
